﻿using System.Reflection;
using Prism.Mvvm;

namespace Iot.RealTimeData.WPF.Prism.Help;

public static class NotifyChanged
{
    /// <summary>
    ///     触发实体所有属性的变更通知
    /// </summary>
    /// <typeparam name="T">实体类型，必须继承自 BindableBase</typeparam>
    /// <param name="entity">需要触发属性变更通知的实体</param>
    public static void NotifyAllPropertiesChanged<T>(this T entity)
        where T : BindableBase
    {
        // 获取私有或受保护的 RaisePropertyChanged 方法
        var method = typeof(T).GetMethod("RaisePropertyChanged", BindingFlags.NonPublic | BindingFlags.Instance, null,
            [typeof(string)], null);
        // 如果方法不存在，则直接返回
        if (method is null) return;

        // 获取实体所有公共实例属性
        var properties = typeof(T).GetProperties(
            BindingFlags.Public | BindingFlags.Instance);
        // 遍历所有属性，触发每个属性的变更通知
        foreach (var property in properties)
        {
            method.Invoke(entity, [property.Name]);
        }
    }
}